import { Fragment, useState,useCallback } from "react";
import useUsers from "./useUsers"
import UserInforModal from "./UserInforModal"

export default ()=>{
  const {data:users,loading,error} = useUsers();
  const [visibleUserId,setVisibleUserId] = useState(null);

  const showUser = useCallback((id)=>{
    setVisibleUserId(id)
  },[])

  const hideUser = useCallback(()=>{
    setVisibleUserId(null)
  },[])

  if(!users || loading) return "Loading..."

  return (
    <Fragment>
      <div className="exp-10-user-list">
        <h2>Users</h2>
        <p>Click name to show details.</p>
        {error && "Fetch failed."}
        <ul>
          {
            users.map((user)=>{
              return (
                <li key={user.id}>
                  <a href="#" onClick={ ()=>showUser(user.id) }>{user.name}</a>
                </li>
              )
            })
          }
        </ul>
        <UserInforModal
          visible={!!visibleUserId}
          userId={visibleUserId}
          onOK={hideUser}
          onCancel={hideUser}
          ></UserInforModal>
      </div>
    </Fragment>
  )
}